<?php

namespace App\Modules\CodeDesigner\Memento;

// 管理者  负责保存好备忘录中memento,不能对备忘录内容进行操作或者检查
class Caretaker
{
    /**
     * @var Originator []
     */
    private $mementos = [];

    private $originator;

    public function __construct(Originator $originator)
    {
        $this->originator = $originator;
    }

    public function backUp(): void
    {
        echo "\nCaretaker: Saving Originator's state...\n";
        $this->mementos[] = $this->originator->save();
    }

    public function undo(): void
    {
        if (empty($this->mementos)) {
            return ;
        }

        $memento = array_pop($this->mementos);
        echo "Caretaker: Restoring state to: " . $memento->getName() . "\n";
        try {
            $this->originator->restore($memento);
        } catch (\Exception $exception) {
            $this->undo();
        }
    }

    public function showHistory(): void
    {
        echo "Caretaker: Here's the list of mementos:\n";
        foreach ($this->mementos as $memento) {
            echo $memento->getName() . "\n";
        }
    }
}